package com.shop.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 
 * @ClassName: Base64Util
 * @Description: Base64工具类
 * @author Kevin.Lv
 * @date 2015年3月6日 下午2:30:19
 * 
 */
@SuppressWarnings("restriction")
public class Base64Utils {

    /**
     * 
     * @Title: object2String @Description: 将一个对象转换成Base64加密后的字符串 @param @param obj 对象 @param @return
     * 字符串 @return String @throws
     */
    public static String object2String(Object obj) {

        String objBody = null;
        ByteArrayOutputStream baops = null;
        ObjectOutputStream oos = null;
        try {
            baops = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baops);
            oos.writeObject(obj);
            byte[] bytes = baops.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            objBody = encoder.encode(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null)
                    oos.close();
                if (baops != null)
                    baops.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return objBody;
    }

    /**
     * 
     * @Title: getObjectFromString @Description: 将一个字符串对象转成Java对象 @param @param str
     * 加密后的字符串 @param @param clazz 要映射的Java对象 @param @return Java对象 @return T @throws
     */
    @SuppressWarnings({ "unchecked" })
    public static <T extends Serializable> T getObjectFromString(String str, Class<T> clazz) {

        ObjectInputStream ois = null;
        T obj = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            ois = new ObjectInputStream(new BufferedInputStream(
                    new ByteArrayInputStream(decoder.decodeBuffer(new String(str.getBytes(), "utf-8")))));
            obj = (T) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null)
                    ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

}
